package com.supporter.sysbench.work;

import com.supporter.sysbench.Command;
import com.supporter.sysbench.ConnectionPoolContext;
import com.supporter.sysbench.GlobalProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author xunaidong
 * @date 2021/8/8
 */
public class Worker implements Runnable {
    private final static Logger log = LoggerFactory.getLogger(Worker.class);
    private final GlobalProperties globalProperties;
    private final SQLExecutor sqlExecutor;
    private final int index;

    public Worker(GlobalProperties globalProperties, SQLExecutor sqlExecutor, int index) {
        this.globalProperties = globalProperties;
        this.sqlExecutor = sqlExecutor;
        this.index = index;
    }

    @Override
    public void run() {
        if (Command.PREPARE == globalProperties.getCommand()) {
            sqlExecutor.prepareData(index, globalProperties.getTableData());
            return;
        }
        long now = System.currentTimeMillis();

        if (Command.READ_ONLY == globalProperties.getCommand()) {
            for (; ; ) {
                if (System.currentTimeMillis() - now > globalProperties.getDuration() * 1000) {
                    log.info("测试时间到,停止业务测试......");
                    break;
                } else {
                    sqlExecutor.readTest(globalProperties.getTableNumber(), globalProperties.getTableData());
                }
            }
        }
        if (Command.READ_WRITE == globalProperties.getCommand()) {
            for (; ; ) {
                if (System.currentTimeMillis() - now > globalProperties.getDuration() * 1000) {
                    log.info("测试时间到,停止业务测试......");
                    break;
                } else {
                    sqlExecutor.readAndWriteTest(globalProperties.getTableNumber(), globalProperties.getTableData());
                }
            }
        }
    }

}
